package com.jt;


import redis.clients.jedis.Jedis;

import java.util.Map;
import java.util.UUID;

public class SSODemo01 {
    static String doLogin(String username,String password){
        //1.判定参数的合法性
        if (username == null || "".equals(username))
            throw new IllegalArgumentException("用户名不能为空");
        if(password == null || "".equals(password))
            throw new IllegalArgumentException("密码不能为空");
        //2.判定用户是否存在
        if(!"tony".equals(username))
            throw new RuntimeException("用户不存在");
        //3.判定密码是否正确
        if(!"123456".equals(password))
            throw new RuntimeException("密码不正确");
        //4.将用户信息存储到Redis
        Jedis jedis = JedisDataSource.getConnection();
        String token = UUID.randomUUID().toString();
        jedis.hset(token, "username","tony");
        jedis.hset(token, "permission","sys:resource:list");
        //5.返回token
        return token ;

    }
    public static Object doGetResource(String token ){
        //1.检验token是否为空
        if (token == null || "".equals(token))
            throw new IllegalArgumentException("请先登录");
        //2.基于token查询用户信息
        Jedis jedis = JedisDataSource.getConnection();
        Map<String, String> user = jedis.hgetAll(token);
        //3.加入用户信息是存在，则表示认证已通过
        if (user == null ||user.size()==0)
            throw new RuntimeException("登录超时，请重新登录");
        //4.判定用户是否有资源的访问权限，没有则抛出异常
        String permission = user.get("permission");
        if ("sys:resource:list".equals(permission))
            throw new RuntimeException("没有此资源的访问权限");
        //5.返回你要访问的资源
        return "123456";
    }
    public static void main(String[] args) {
        String username = "tony";
        String password ="123456";
        String token = doLogin(username,password);
        System.out.println("token="+token);

    }
}
